package net.vinote.smart.platform.service;

import java.sql.SQLException;
import java.util.logging.Level;

import net.vinote.smart.platform.comm.PlatformConst;
import net.vinote.smart.platform.module.log.RunLogger;
import net.vinote.smart.platform.module.security.Aes128;
import net.vinote.smart.platform.module.security.Base64;
import net.vinote.smart.platform.service.util.Permission;
import net.vinote.smart.platform.service.util.Permission.PermissionEnum;

public class GeneralTools {

	/**
	 * 获取指定数据库对应的驱动
	 * 
	 * @param dbType
	 * @return
	 */
	public static String getDriver(String dbType) {
		String driver = null;
		if (dbType == null)
			dbType = "";
		String type = dbType.toLowerCase();
		if (PlatformConst.MYSQL.equalsIgnoreCase(type)) {
			driver = PlatformConst.MYSQL_DRIVER;
		}
		return driver;
	}

	/**
	 * 获取数据库URL
	 * 
	 * @param host
	 *            数据库主机
	 * @param port
	 *            数据库服务端口号
	 * @param dbName
	 *            数据库实例
	 * @param dbType
	 *            数据库类型
	 * @return
	 */
	public static String getDataBaseUrl(String host, int port, String dbName,
			String dbType) {
		String url = null;
		if (dbType == null)
			dbType = "";
		String type = dbType.toLowerCase();
		if (PlatformConst.MYSQL.equalsIgnoreCase(type)) {
			url = "jdbc:mysql://" + host + ":" + port + "/" + dbName;
		}
		return url;
	}

	/**
	 * 重新加载SRE信息
	 */
	@Permission(PermissionEnum.SMART_ADMINISTRATOR)
	public String reloadSRE() throws SQLException {
		SRE sre = SRE.getInstance();
		return sre.initializ() ? PlatformConst.SUCCESS : PlatformConst.FAIL;
	}

	public static String encrypt(String str) {
		return encrypt(str, SRE.getSystemParameter().getAes128Key());
	}

	public static String encrypt(String str, String key) {
		try {
			byte[] encryptByte = Aes128.encrypt(str.getBytes(), key.getBytes());
			return Base64.byteArrayToBase64(encryptByte);
		} catch (Exception e) {
			RunLogger.getLogger().log(Level.SEVERE, e.getMessage(), e);
			return str;
		}
	}

	public static String decrypt(String str) {
		return decrypt(str, SRE.getSystemParameter().getAes128Key());
	}

	public static String decrypt(String str, String key) {
		try {
			return new String(
					Aes128.decrypt(Base64.decode(str), key.getBytes()));
		} catch (Exception e) {
			RunLogger.getLogger().log(Level.SEVERE, e.getMessage(), e);
			return str;
		}
	}

	/**
	 * 生成Aes12秘钥字符串,若传入的key不足16为，则在末尾补=
	 * 
	 * @param key
	 *            长度小于等于16的字符串
	 * @return
	 */
	public static String getAesKey(String key) {
		if (key == null || key.length() > PlatformConst.AES_KEY_LENGTH) {
			throw new IllegalArgumentException("key:" + key);
		}
		StringBuffer sb = new StringBuffer(key);
		int fillSize = PlatformConst.AES_KEY_LENGTH - key.length();
		while (fillSize-- > 0) {
			sb.append('=');
		}
		return sb.toString();
	}
}
